package com.lt.flashcard.webservice.filter;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.Transaction;
import org.zkoss.zkplus.hibernate.HibernateUtil;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

@SuppressWarnings("deprecation")
public class RestfulResponseFilter implements ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        Transaction transaction = HibernateUtil.getSessionFactory().getCurrentSession().getTransaction();
        Object resultValue = response.getEntity();
        Map<String, Object> returnedData = new HashMap<String, Object>(2);
        if (resultValue instanceof String && resultValue.toString().startsWith("Error")) {
            transaction.rollback();
            returnedData.put("success", false);
            returnedData.put("errorMsg", resultValue.toString());
        } else {
            transaction.commit();
            returnedData.put("success", true);
            returnedData.put(getDataKey(request.getPath()), resultValue);
        }
        response.setEntity(returnedData);
        return response;
    }

    private String getDataKey(String path) {
        if (path.endsWith("/list")) {
            return "items";
        }
        if (path.contains("/detail/")) {
            return "item";
        }
        if (path.endsWith("/save") || path.endsWith("/clone")) {
            return "id";
        }
        if (path.endsWith("/learnt")) {
            return "learnLevel";
        }
        if (path.endsWith("/resetLearnStatus")) {
            return "status";
        }
        if (path.endsWith("login") || path.endsWith("register") || path.endsWith("forgotPassword")) {
            return "user";
        }
        return "data";
    }
}